package com.vegetable.modules.controller.sys;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.Assert;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.form.PasswordForm;
import com.vegetable.modules.form.sys.UserQueryForm;
import com.vegetable.modules.form.sys.UserListForm;
import com.vegetable.modules.service.sys.SysUserRoleService;
import com.vegetable.modules.service.sys.SysUserService;
import com.vegetable.modules.service.wx.WxDepartmentService;
import com.vegetable.modules.vo.sys.SysUserVO;
import com.vegetable.modules.vo.sys.SysUserInfoVO;
import com.vegetable.modules.entity.wx.WxDepartment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
@AllArgsConstructor
@Api(value = "系统用户", tags = "系统用户")
public class SysUserController extends AbstractController {
	private SysUserService sysUserService;
	private SysUserRoleService sysUserRoleService;
	private WxDepartmentService wxDepartmentService;
	
	/**
	 * 所有用户列表（包含部门信息）
	 * @param form 查询条件，包括用户名、创建用户ID、状态和部门ID等
	 */
	@GetMapping("/list")
	@ApiOperation(value = "条件查询用户列表（包含部门信息）", notes = "条件查询用户列表（包含部门信息）")
	public R list(UserQueryForm form){
		//只有超级管理员，才能查看所有管理员列表
		/*if(getUserId() != Constant.SUPER_ADMIN){
			form.setCreateUserId(getUserId());
		}*/

		IPage<SysUserVO> page = sysUserService.queryPageWithDepartments(form);

		return R.data(page);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	@ApiOperation(value = "获取登录的用户信息", notes = "获取登录的用户信息")
	public R info(){
		SysUserEntity user = getUser();
		SysUserInfoVO userInfoVO = new SysUserInfoVO();
		
		// 复制用户信息（不包括密码）
		userInfoVO.setUserId(user.getUserId());
		userInfoVO.setUsername(user.getUsername());
		userInfoVO.setRealName(user.getRealName());
		userInfoVO.setEmail(user.getEmail());
		userInfoVO.setMobile(user.getMobile());
		userInfoVO.setRoleIdList(user.getRoleIdList());
		userInfoVO.setCreateTime(user.getCreateTime());
		
		// 获取用户所属部门ID列表
		List<WxDepartment> departments = wxDepartmentService.getSysUserDepartments(user.getUserId());
		List<Long> departmentIds = departments.stream().map(WxDepartment::getId).collect(java.util.stream.Collectors.toList());
		userInfoVO.setDepartmentIds(departmentIds);
		
		return R.data(userInfoVO);
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog(value = "修改密码")
	@PostMapping("/password")
	@ApiOperation(value = "修改密码", notes = "修改密码")
	public R password(@RequestBody PasswordForm form){
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");
		
		//sha256加密
//		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		//sha256加密
//		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();
				
		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), form.getPassword(), form.getNewPassword());
		if(!flag){
			return R.fail("原密码不正确");
		}
		
		return R.status(true);
	}
	
	/**
	 * 用户信息
	 */
	@GetMapping("/infoForRole")
	@ApiOperation(value = "用户信息", notes = "用户信息")
	public R infoForRole(Long userId){
		SysUserEntity user = sysUserService.getById(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return R.data(user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog(value = "保存用户")
	@PostMapping("/save")
	@ApiOperation(value = "保存用户", notes = "保存用户")
	public R save(@RequestBody SysUserEntity user){
		user.setCreateUserId(getUserId());
		sysUserService.saveUser(user);
		
		return R.status(true);
	}
	
	/**
	 * 修改用户
	 */
	@SysLog(value = "修改用户")
	@PostMapping("/update")
	@ApiOperation(value = "修改用户", notes = "修改用户")
	public R update(@RequestBody SysUserEntity user){
		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		
		return R.status(true);
	}
	
	/**
	 * 删除用户
	 */
	@SysLog(value = "删除用户")
	@GetMapping("/delete")
	@ApiOperation(value = "删除用户", notes = "删除用户")
	public R delete(Long id){
		if(id == 1L){
			return R.fail("系统管理员不能删除");
		}
		if(id == getUserId()){
			return R.fail("当前用户不能删除");
		}
		sysUserService.removeById(id);
		return R.status(true);
	}
}
